package com.cskaoyan.wordmemorize.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cskaoyan.wordmemorize.common.aspect.operate.OperateLog;
import com.cskaoyan.wordmemorize.common.constant.ResultCodeEnum;
import com.cskaoyan.wordmemorize.common.exception.BusinessException;
import com.cskaoyan.wordmemorize.converter.VocChapterConverter;
import com.cskaoyan.wordmemorize.dao.entity.VocChapterDO;
import com.cskaoyan.wordmemorize.dao.mapper.VocChapterMapper;
import com.cskaoyan.wordmemorize.dao.entity.VocBookDO;
import com.cskaoyan.wordmemorize.dao.mapper.VocBookMapper;
import com.cskaoyan.wordmemorize.dto.admin.DeleteChapterOperateDTO;
import com.cskaoyan.wordmemorize.dto.admin.PageDTO;
import com.cskaoyan.wordmemorize.dto.admin.VocChapterDTO;
import com.cskaoyan.wordmemorize.request.BatchDeleteCommand;
import com.cskaoyan.wordmemorize.request.VocChapterCommand;
import com.cskaoyan.wordmemorize.request.VocChapterPageRequest;
import com.cskaoyan.wordmemorize.service.VocChapterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class VocChapterServiceImpl implements VocChapterService {

    @Autowired
    VocChapterConverter vocChapterConverter;
    @Autowired
    VocChapterMapper vocChapterMapper;
    @Autowired
    VocBookMapper vocBookMapper;

    /**
     * 分页查询章节列表
     *
     * @param pageQuery
     * @return
     */
    @Override
    public PageDTO<VocChapterDTO> getChapterPage(VocChapterPageRequest pageQuery) {
        LambdaQueryWrapper<VocChapterDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(VocChapterDO::getIsDeleted, 0);

        // 如果请求中包含书籍ID，则添加书籍ID的查询条件
        if (StringUtils.isNotBlank(pageQuery.getBookId())) {
            wrapper.eq(VocChapterDO::getBookId, pageQuery.getBookId());
        }

        // 如果请求中包含关键词，则添加章节名称的模糊查询条件
        if (StringUtils.isNotBlank(pageQuery.getKeyword())) {
            wrapper.like(VocChapterDO::getChapterName, pageQuery.getKeyword());
        }
        // 按照 sortBy 字段升序排序
        wrapper.orderByAsc(VocChapterDO::getSortBy);

        // 检查分页参数是否为空(区分全查和分页查)
        if (pageQuery.getPageNum() == null || pageQuery.getCount() == null) {
            List<VocChapterDO> all = vocChapterMapper.selectList(wrapper);
            return vocChapterConverter.vocChapterDOs2Page(all, (long) all.size());
        } else {
            Page<VocChapterDO> page = new Page<>(pageQuery.getPageNum(), pageQuery.getCount());
            Page<VocChapterDO> result = vocChapterMapper.selectPage(page, wrapper);
            return vocChapterConverter.vocChapterDOs2Page(result.getRecords(), result.getTotal());
        }
    }

    /**
     * 添加章节
     *
     * @param command
     */
    @Override
    @Transactional
    @OperateLog(dataType = "章节", operateType = 1, description = "新增章节")
    public void addChapter(VocChapterCommand command) {
        if (StringUtils.isBlank(command.getBookId())) {
            // 书籍id不能为空
            throw new BusinessException(ResultCodeEnum.PARAM_ERROR);
        }
        if (StringUtils.isBlank(command.getChapterName())) {
            // 章节名称不能为空
            throw new BusinessException(ResultCodeEnum.PARAM_ERROR);
        }
        LambdaQueryWrapper<VocChapterDO> queryWrapper = new LambdaQueryWrapper<>();
        // 查询条件:ID相等、章节名称相等且未被删除
        queryWrapper.eq(VocChapterDO::getBookId, command.getBookId())
                .eq(VocChapterDO::getChapterName, command.getChapterName())
                .eq(VocChapterDO::getIsDeleted, 0);
        // 查询出来的count大于0说明有重复
        if (vocChapterMapper.selectCount(queryWrapper) > 0) {
            // 章节名称不能重复
            throw new BusinessException(ResultCodeEnum.CHAPTER_EXISTED.getMessage(),
                    ResultCodeEnum.CHAPTER_EXISTED.getCode());
        }

        VocChapterDO chapterDO = vocChapterConverter.vocChapterCommand2DO(command);
        chapterDO.setVocCount(0); // 章节包含的单词数量(初始应该为0)
        chapterDO.setIsDeleted(0);
        vocChapterMapper.insert(chapterDO);

        // 新增章节后，书籍的章节数+1
        try {
            Long bookId = Long.valueOf(command.getBookId());
            VocBookDO book = vocBookMapper.selectById(bookId);
            if (book != null) {
                Integer oldCount = book.getChapterCount() == null ? 0 : book.getChapterCount();
                book.setChapterCount(oldCount + 1);
                vocBookMapper.updateById(book);
            }
        } catch (Exception e) {
            // 可以记录日志
        }
    }

    /**
     * 更新章节
     *
     * @param command
     */
    @Override
    @Transactional
    @OperateLog(dataType = "章节", operateType = 4, description = "修改章节")
    public void updateChapter(VocChapterCommand command) {
        if (StringUtils.isBlank(command.getId())) {
            // 章节id不能为空
            throw new BusinessException(ResultCodeEnum.PARAM_ERROR);
        }
        if (StringUtils.isBlank(command.getChapterName())) {
            // 章节名称不能为空
            throw new BusinessException(ResultCodeEnum.PARAM_ERROR);
        }
        // 检查章节是否存在
        VocChapterDO existingChapter = vocChapterMapper.selectById(command.getId());
        if (existingChapter == null || existingChapter.getIsDeleted() == 1) {
            // 章节不存在
            throw new BusinessException(ResultCodeEnum.CHAPTER_NOT_EXISTED);
        }
        LambdaQueryWrapper<VocChapterDO> queryWrapper = new LambdaQueryWrapper<>();
        // 检查章节名称是否重复
        queryWrapper.eq(VocChapterDO::getBookId, existingChapter.getBookId())
                .eq(VocChapterDO::getChapterName, command.getChapterName()) // 章节名称不能重复
                .ne(VocChapterDO::getId, command.getId()) // 章节id不能重复
                .eq(VocChapterDO::getIsDeleted, 0); // 章节未被删除

        // 查询出来的count大于0说明有重复
        if (vocChapterMapper.selectCount(queryWrapper) > 0) {
            // 章节名称不能重复
            throw new BusinessException(ResultCodeEnum.CHAPTER_EXISTED.getMessage(),
                    ResultCodeEnum.CHAPTER_EXISTED.getCode());
        }

        VocChapterDO chapterDO = vocChapterConverter.vocChapterCommand2DO(command);

        // 更新章节的话,包含的单词数量应该不变(有特殊情况再做处理)
        chapterDO.setVocCount(existingChapter.getVocCount());
        chapterDO.setIsDeleted(0); // 设置未删除
        vocChapterMapper.updateById(chapterDO);
    }

    /**
     * 删除章节
     *
     * @param chapterId
     * @return
     */
    @Override
    @Transactional
    @OperateLog(dataType = "章节", operateType = 2, description = "删除章节", logReturnValue = true)
    public DeleteChapterOperateDTO deleteChapter(Long chapterId) {
        if (chapterId == null) {
            throw new BusinessException(
                    ResultCodeEnum.PARAM_ERROR);
        }
        VocChapterDO chapterDO = vocChapterMapper.selectById(chapterId);
        if (chapterDO == null || chapterDO.getIsDeleted() == 1) {
            throw new BusinessException(
                    ResultCodeEnum.CHAPTER_NOT_EXISTED);
        }
        vocChapterMapper.deleteById(chapterId);
        // 删除章节后，书籍的章节数-1
        try {
            Long bookId = chapterDO.getBookId();
            VocBookDO book = vocBookMapper.selectById(bookId);
            if (book != null) {
                Integer oldCount = book.getChapterCount() == null ? 0 : book.getChapterCount();
                book.setChapterCount(Math.max(0, oldCount - 1));
                vocBookMapper.updateById(book);
            }
        } catch (Exception e) {
            // 可以记录日志
        }
        return vocChapterConverter.vocChapterDO2DeleteDTO(chapterDO);
    }

    /**
     * 批量删除章节
     *
     * @param command
     * @return
     */
    @Override
    @Transactional
    @OperateLog(dataType = "章节", operateType = 3, description = "批量删除章节", logReturnValue = true)
    public List<DeleteChapterOperateDTO> deleteChapters(BatchDeleteCommand command) {
        if (command == null || CollectionUtils.isEmpty(command.getIds())) {
            throw new BusinessException(ResultCodeEnum.PARAM_ERROR);
        }
        List<DeleteChapterOperateDTO> deletedChapters = new ArrayList<>();
        for (String idStr : command.getIds()) {
            try {
                Long id = Long.valueOf(idStr);
                VocChapterDO chapterDO = vocChapterMapper.selectById(id);
                if (chapterDO != null && chapterDO.getIsDeleted() != 1) {
                    vocChapterMapper.deleteById(id);
                    deletedChapters.add(vocChapterConverter.vocChapterDO2DeleteDTO(chapterDO));
                    // 删除章节后，书籍的章节数-1
                    try {
                        Long bookId = chapterDO.getBookId();
                        VocBookDO book = vocBookMapper.selectById(bookId);
                        if (book != null) {
                            Integer oldCount = book.getChapterCount() == null ? 0 : book.getChapterCount();
                            book.setChapterCount(Math.max(0, oldCount - 1));
                            vocBookMapper.updateById(book);
                        }
                    } catch (Exception e) {
                        // 可以记录日志
                    }
                }
            } catch (NumberFormatException e) {
                // 可以记录日志，说明有非法ID
            }
        }
        return deletedChapters;
    }
}
